import {_decorator, Component, Node, Prefab} from 'cc';
import {SkillIconController} from "db://assets/scripts/ui/pause/SkillIconController";
import {CSVManager} from "db://assets/scripts/common/CSVManager";
import {Constants} from "db://assets/scripts/common/Constants";
import {PoolManager} from "db://assets/scripts/common/PoolManager";
import {PlayerDataManager} from "db://assets/scripts/common/PlayerDataManager";
import {SkillConverter} from "db://assets/scripts/data/converter/SkillConverter";

const {ccclass, property} = _decorator;

/**
 * 技能列表控制器
 */
@ccclass('SkillsController')
export class SkillsController extends Component {
    /**
     * 技能预制体
     */
    @property(Prefab)
    public skillIconPrefab: Prefab;

    /**
     * 回调
     */
    private callback: Function;

    /**
     * 初始化技能列表
     *
     * @param callback 回调
     */
    public init(callback?: Function) {
        // 回调
        this.callback = callback;

        // 玩家已解锁的技能列表
        let unLockSkillIds = PlayerDataManager.getInstance().getPlayer().skillIds.concat();

        // 冻结所有子节点
        this.node.children.forEach((ndChild: Node) => {
            ndChild.active = false;
        })

        // 每次技能展示数量不能超过[MAX_SKILL_ICON_NUM]个
        if (unLockSkillIds.length > Constants.MAX_SKILL_ICON_NUM) {
            unLockSkillIds.length = Constants.MAX_SKILL_ICON_NUM;
        }

        // 所有技能
        let playerSkillCSV = CSVManager.getInstance().getTable("playerSkill");
        let playerSkills = SkillConverter.convertFromCSV(playerSkillCSV);

        unLockSkillIds.forEach((skillId: string, index: number) => {
            let child: Node;

            // 将预制体转为节点
            if (index >= this.node.children.length) {
                child = PoolManager.getInstance().getNode(this.skillIconPrefab, this.node);
            } else {
                child = this.node.children[index];
            }

            // 激活节点
            child.active = true;

            // 展示技能
            let skill = playerSkills.find(value => value.id === skillId);
            let skillIconController = child.getComponent(SkillIconController);
            skillIconController.init(index, skill, this.callback);
        })
    }
}